package com.example.socketfileupload;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author zhanghui
 * @date 2021/12/6 10:34
 */
public class Client {
    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new FileInputStream("socketFileUpload.jpeg");
            String serverIp = "127.0.0.1";
            int serverPort = 9999;

            System.out.println("客户端启动");
            // 连接服务器
            Socket socket = new Socket(serverIp, serverPort);
            System.out.println("已连接服务器");

            // 字节输出流包装为数据输出流
            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
            // 发送文件类型
            dataOutputStream.writeUTF("jpeg");

            byte[] buffer = new byte[1024];
            int readLength = 0;
            while ((readLength = fileInputStream.read(buffer)) > 0) {
                dataOutputStream.write(buffer, 0, readLength);
            }
            dataOutputStream.flush();
            dataOutputStream.close();
            fileInputStream.close();
            socket.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }
}
